/*
 * Copyright (c) 2006, 2021, webrx.cn All rights reserved.
 *
 */
package cn.webrx.config;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import javax.servlet.DispatcherType;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.swing.*;
import java.util.EnumSet;

/**
 * <p>Project: mybatis2021 - WebAppConfig
 * <p>Powered by webrx On 2021-07-19 16:31:49
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 15
 */

public class WebAppConfig implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext c) throws ServletException {

        //配置Spring ContextLoaderListener 监听器
        var context = new AnnotationConfigWebApplicationContext();
        context.register(SpringConfig.class);
        c.addListener(new ContextLoaderListener(context));



        //web.xml 加载springmvc.xml
        context.register(SpringMVCConfig.class);
        //web.xml 加载 applicationContext.xml
        context.register(SpringConfig.class);


        DispatcherServlet servlet = new DispatcherServlet(context);
        //在启动web项目注册DispatcherServlet
        ServletRegistration.Dynamic registration = c.addServlet("dispatcher", servlet);
        registration.setLoadOnStartup(1);
        registration.addMapping("/");

        //注册编码过滤器 过滤地址：可以解决PrintWriter输出中文乱码 或 post提交中文乱码
        var cf = new CharacterEncodingFilter("utf-8", true);
        var regf = c.addFilter("cf", cf);
        regf.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/*");
    }
}
